package org.luxor.sdk.common;

import com.google.gson.reflect.TypeToken;
import org.luxor.sdk.auth.v1.AccessToken;
import org.luxor.sdk.auth.v1.OAuth2AccessToken;
import org.luxor.sdk.common.exception.LuxorCloudSDKException;
import org.luxor.sdk.common.models.ResponseModel;
import org.luxor.sdk.common.profile.ClientProfile;
import org.luxor.sdk.common.profile.HttpMethod;

import java.lang.reflect.Type;
import java.util.HashMap;

/**
 * 应用级客户端
 *
 * @author Mr.yan  @date 2021/9/13
 */
public class CommonAppClient extends AbstractClient {

    @Override
    public AccessToken getAuthorization(HashMap<String, String> headers, byte[] bodyPayload) throws LuxorCloudSDKException {
        if (accessToken != null && accessToken.expiresTimeMs != 0 && accessToken.expiresTimeMs < System.currentTimeMillis()) {
            return accessToken;
        }
        HashMap<String, String> params = new HashMap<>();
        params.put("grant_type", "client_credentials");
        params.put("client_id", getCredential().getClientId());
        params.put("client_secret", getCredential().getClientSecret());

        String url = "http://127.0.0.1:2001/oauth/token";
        String canonicalQueryString = formatQueryParams(params, bodyPayload);
        String respBody = getResponseBody(HttpMethod.POST, url + "?" + canonicalQueryString, headers, bodyPayload);
        Type errType = new TypeToken<ResponseModel<OAuth2AccessToken>>() {
        }.getType();
        ResponseModel<OAuth2AccessToken> errResp = gson.fromJson(respBody, errType);
        accessToken.accessToken = errResp.data.accessToken;
        accessToken.tokenType = errResp.data.tokenType;
        accessToken.expiresIn = errResp.data.expiresIn;
        if (errResp.data.expiresIn != 0) {
            accessToken.expiresTimeMs = System.currentTimeMillis() + errResp.data.expiresIn * 1000;
        }
        return accessToken;
    }

    public CommonAppClient(String version, Credential credential) {
        this(version, credential, "global", new ClientProfile());
    }

    public CommonAppClient(String version, Credential credential, String region) {
        this(version, credential, region, new ClientProfile());
    }

    public CommonAppClient(String version, Credential credential, String region, ClientProfile profile) {
        super(version, credential, region, profile);
    }

}